package ldh.im.base.service;

import io.netty.channel.Channel;
import ldh.im.ImConfig;
import ldh.im.base.CacheUserManager;
import ldh.im.base.ImSession;
import ldh.im.dto.base.ErrorResp;
import ldh.im.dto.business.LoginResp;
import ldh.im.dto.business.ReConnection;
import ldh.im.util.RandomCharacter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

public class ReConnectionBusinessService implements BusinessService<ReConnection> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReConnectionBusinessService.class);

    @Override
    public void handle(ImSession imSession, ReConnection reConnection) {
        Channel channel = imSession.getChannel();
        LOGGER.info(String.format("%s reConnection success!!!!", reConnection.getAuthToken()));

        Long userId = Math.round(Double.MAX_VALUE);

        String authToken = (String) CacheUserManager.getInstance().getCache(userId, "AUTH_TOKEN");
        if (authToken == null || !authToken.equals(reConnection.getAuthToken())) {
            channel.writeAndFlush(new ErrorResp(103, "请登录"));
        }

        imSession.put(ImConfig.CHANNEL_ID, channel.id());

        LoginResp loginRec = new LoginResp();
        loginRec.setLocalSeq(reConnection.getLocalSeq());
        loginRec.setUserId(1111111L);
        loginRec.setServerDateTime(LocalDateTime.now());
        loginRec.setSuccessDataTime(LocalDateTime.now());
        loginRec.setAuthToken(buildAuth(20));
        loginRec.setAuthCode((int)(Math.random() * 100000));

        CacheUserManager.getInstance().setCache(userId, ImConfig.AUTH_TOKEN, loginRec.getAuthToken());
        CacheUserManager.getInstance().setCache(userId, ImConfig.AUTH_CODE, loginRec.getAuthCode());
        imSession.put(ImConfig.AUTH_CODE, loginRec.getAuthCode());

        channel.writeAndFlush(loginRec);
    }

    private String buildAuth(int length) {
        return RandomCharacter.getRandomCharacter(length);
    }
}
